﻿// Copyright (c) Microsoft Corporation and Contributors.
// Licensed under the MIT License.

using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.Devices.Enumeration;
using Windows.Devices.HumanInterfaceDevice;
using Windows.Devices.SerialCommunication;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Storage.Streams;
using static System.Net.Mime.MediaTypeNames;
using System.Text.RegularExpressions;
using Microsoft.UI.Input;
using Vanara.PInvoke;
using Windows.Graphics;
using Microsoft.UI;
using WinRT.Interop;
using Microsoft.UI.Windowing;
using static SerialCommand.BackStyleControl;
using System.Xml.Linq;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace SerialCommand
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class HomePage : Page
    {
        private ObservableCollection<DeviceListEntry> listOfDevices;
        private Dictionary<DeviceWatcher, String> mapDeviceWatchersToDeviceSelector;
        // Has all the devices enumerated by the device watcher?
        private Boolean isAllDevicesEnumerated;
        uint baudRate = 921600;
        ushort dataBits = 8;
        bool recivce;
        Thread thread;
        StringBuilder stringBuilder = new StringBuilder(1024 * 10240);
        StringWriter stringWriter;
        SerialCommRegex serialCommRegex;
        static public HomePage Current;
        public HomePage()
        {
            this.InitializeComponent();
            listOfDevices = new ObservableCollection<DeviceListEntry>();
            mapDeviceWatchersToDeviceSelector = new Dictionary<DeviceWatcher, String>();
            isAllDevicesEnumerated = false;
            stringWriter = new StringWriter(stringBuilder);
            serialCommRegex = SerialCommRegex.Current;
            Current = this;
        }
        ~HomePage()
        {
        }
        private void OnDeviceConnected(EventHandlerDevice sender, DeviceInformation deviceInformation)
        {
            if (isAllDevicesEnumerated)
            {
                SelectDeviceInList(EventHandlerDevice.Current.DeviceInformation.Id);
            }

            if (EventHandlerDevice.Current.Device.PortName != "")
            {
                MainWindow.Current.NotifyUpdate("连接到 - " +
                                    EventHandlerDevice.Current.Device.PortName +
                                    " - " +
                                    EventHandlerDevice.Current.DeviceInformation.Name, InfoBarSeverity.Informational);
            }
            else
            {
                MainWindow.Current.NotifyUpdate("连接到 - " +
                                    EventHandlerDevice.Current.DeviceInformation.Name, InfoBarSeverity.Informational);
            }
            string name = "打开串口";
            if (EventHandlerDevice.Current.Device != null)
            {
                EventHandlerDevice.Current.Device.BaudRate = baudRate;
                EventHandlerDevice.Current.Device.DataBits = dataBits;
                EventHandlerDevice.Current.Device.ReadTimeout = TimeSpan.FromMilliseconds(10);
                EventHandlerDevice.Current.Device.WriteTimeout = TimeSpan.FromMilliseconds(10);
                thread = new Thread(async () =>
                {
                    recivce = true;
                    int charSize = 20000;
                    Char[] chars = new Char[charSize];
                    dataWriter = new DataWriter(EventHandlerDevice.Current.Device.OutputStream);
                    dataReader = new DataReader(EventHandlerDevice.Current.Device.InputStream);
                    dataReader.InputStreamOptions = InputStreamOptions.Partial;
                    while (recivce)
                    {
                        byte[] temp = await serialRead();
                        if (temp != null)
                        {
                            string recviceString = Encoding.UTF8.GetString(temp);
                            ThreadPool.QueueUserWorkItem(new WaitCallback(state =>
                            {
                                serialCommRegex.execComm(recviceString);
                            }));
                            stringWriter.Write(recviceString);
                        }
                        if (stringBuilder.Length >= charSize)
                            stringBuilder.CopyTo(stringBuilder.Length - charSize, chars, charSize);
                        else
                            stringBuilder.CopyTo(0, chars, stringBuilder.Length);
                        MainWindow.Current.invoke(() =>
                        {
                            string s = new string(chars);
                            recivceText.Text = s;
                            HomeViewMode.RecviceLength = (uint)stringBuilder.Length;
                            recivceTextScroll.ScrollToVerticalOffset(recivceTextScroll.ExtentHeight);
                        });
                    }
                });
                thread.Start();
                name = "关闭串口";
            }

            myButton.Content = name;
        }
        private void OnDeviceClosing(EventHandlerDevice sender, DeviceInformation deviceInformation)
        {
            MainWindow.Current.invoke(
                new DispatcherQueueHandler(() =>
                {
                    recivce = false;
                    myButton.Content = "打开串口";
                    MainWindow.Current.NotifyUpdate("串口打开失败", InfoBarSeverity.Error);
                    dataWriter.Dispose();
                    dataReader.Dispose();
                    dataWriter = null;
                    dataReader = null;
                }));
        }
        private void InitializeDeviceWatchers()
        {
            // FAST HID Device
            var SerialDeviceSelector = SerialDevice.GetDeviceSelector();
            // 创建设备状态观察者
            var SerialDeviceWatcher = DeviceInformation.CreateWatcher(SerialDeviceSelector);
            // 添加观察者事件回调
            AddDeviceWatcher(SerialDeviceWatcher, SerialDeviceSelector);
        }
        private void AddDeviceWatcher(DeviceWatcher deviceWatcher, String deviceSelector)
        {
            deviceWatcher.Added += new TypedEventHandler<DeviceWatcher, DeviceInformation>(this.OnDeviceAdded);
            deviceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(this.OnDeviceRemoved);
            deviceWatcher.EnumerationCompleted += new TypedEventHandler<DeviceWatcher, Object>(this.OnDeviceEnumerationComplete);

            mapDeviceWatchersToDeviceSelector.Add(deviceWatcher, deviceSelector);
        }
        private void StartDeviceWatchers()
        {
            // Start all device watchers
            isAllDevicesEnumerated = false;

            foreach (DeviceWatcher deviceWatcher in mapDeviceWatchersToDeviceSelector.Keys)
            {
                if ((deviceWatcher.Status != DeviceWatcherStatus.Started)
                    && (deviceWatcher.Status != DeviceWatcherStatus.EnumerationCompleted))
                {
                    deviceWatcher.Start();
                }
            }
        }
        private void OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInformation)
        {
            MainWindow.Current.invoke(
                new DispatcherQueueHandler(() =>
                {
                    MainWindow.Current.NotifyUpdate("设备接入 - " + deviceInformation.Name, InfoBarSeverity.Informational);

                    AddDeviceToList(deviceInformation, mapDeviceWatchersToDeviceSelector[sender]);
                }));
        }
        private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate)
        {
            MainWindow.Current.invoke(
                new DispatcherQueueHandler(() =>
                {
                    MainWindow.Current.NotifyUpdate("设备已移除", InfoBarSeverity.Informational);
                    RemoveDeviceFromList(deviceInformationUpdate.Id);
                }));
        }
        private void OnDeviceEnumerationComplete(DeviceWatcher sender, Object args)
        {
            MainWindow.Current.invoke(
                new DispatcherQueueHandler(() =>
                {
                    isAllDevicesEnumerated = true;

                    // If we finished enumerating devices and the device has not been connected yet, the OnDeviceConnected method
                    // is responsible for selecting the device in the device list (UI); otherwise, this method does that.
                    if (EventHandlerDevice.Current.IsDeviceConnected)
                    {
                        SelectDeviceInList(EventHandlerDevice.Current.DeviceInformation.Id);
                        if (EventHandlerDevice.Current.Device.PortName != "")
                        {
                            MainWindow.Current.NotifyUpdate("连接到 - " +
                                                EventHandlerDevice.Current.Device.PortName +
                                                " - " +
                                                EventHandlerDevice.Current.DeviceInformation.Name, InfoBarSeverity.Informational);
                        }
                        else
                        {
                            MainWindow.Current.NotifyUpdate("连接到 - " +
                                                EventHandlerDevice.Current.DeviceInformation.Name, InfoBarSeverity.Informational);
                        }
                    }
                    else if (EventHandlerDevice.Current.IsEnabledAutoReconnect && EventHandlerDevice.Current.DeviceInformation != null)
                    {
                        MainWindow.Current.NotifyUpdate("等待重新连接设备 -  " + EventHandlerDevice.Current.DeviceInformation.Name, InfoBarSeverity.Informational);
                    }
                    else
                    {
                        MainWindow.Current.NotifyUpdate("没有设备连接", InfoBarSeverity.Informational);
                    }
                }));
        }

        private DeviceListEntry FindDevice(String deviceId)
        {
            if (deviceId != null)
            {
                foreach (DeviceListEntry entry in listOfDevices)
                {
                    if (entry.DeviceInformation.Id == deviceId)
                    {
                        return entry;
                    }
                }
            }

            return null;
        }
        private void AddDeviceToList(DeviceInformation deviceInformation, String deviceSelector)
        {
            // search the device list for a device with a matching interface ID
            var match = FindDevice(deviceInformation.Id);

            // Add the device if it's new
            if (match == null)
            {
                // Create a new element for this device interface, and queue up the query of its
                // device information
                match = new DeviceListEntry(deviceInformation, deviceSelector);

                // Add the new element to the end of the list of devices
                listOfDevices.Add(match);
            }
        }
        private void RemoveDeviceFromList(String deviceId)
        {
            // Removes the device entry from the interal list; therefore the UI
            var deviceEntry = FindDevice(deviceId);

            listOfDevices.Remove(deviceEntry);
        }
        private void SelectDeviceInList(String deviceIdToSelect)
        {
            // Don't select anything by default.
            ConnectDevices.SelectedIndex = -1;

            for (int deviceListIndex = 0; deviceListIndex < listOfDevices.Count; deviceListIndex++)
            {
                if (listOfDevices[deviceListIndex].DeviceInformation.Id == deviceIdToSelect)
                {
                    ConnectDevices.SelectedIndex = deviceListIndex;

                    break;
                }
            }
        }
        DataWriter dataWriter;
        DataReader dataReader;
        private async void myButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceListEntry entry = null;
            entry = (DeviceListEntry)ConnectDevices.SelectedItem;
            if (entry != null)
            {
                ConnectDevices.IsEnabled = false;
                if (!EventHandlerDevice.Current.IsDeviceConnected)
                {
                    // Create an EventHandlerForDevice to watch for the device we are connecting to
                    EventHandlerDevice.CreateNewEventHandlerDevice();
                    // Get notified when the device was successfully connected to or about to be closed
                    EventHandlerDevice.Current.OnDeviceConnected = this.OnDeviceConnected;
                    EventHandlerDevice.Current.OnDeviceClose = this.OnDeviceClosing;

                    // It is important that the FromIdAsync call is made on the UI thread because the consent prompt, when present,
                    // can only be displayed on the UI thread. Since this method is invoked by the UI, we are already in the UI thread.
                    Boolean openSuccess = await EventHandlerDevice.Current.OpenDeviceAsync(entry.DeviceInformation, entry.DeviceSelector);
                }
                else
                {
                    ConnectDevices.IsEnabled = true;
                    EventHandlerDevice.Current.IsEnabledAutoReconnect = false;
                    EventHandlerDevice.Current.CloseDevice();
                }
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Window window = WindowHelper.GetWindowForElement(this);
            window.ExtendsContentIntoTitleBar = true;
            window.SetTitleBar(AppTitleBar);
            EventHandlerDevice.Current.OnDeviceConnected = this.OnDeviceConnected;
            EventHandlerDevice.Current.OnDeviceClose = this.OnDeviceClosing;
            // Initialize the desired device watchers so that we can watch for when devices are connected/removed
            InitializeDeviceWatchers();
            StartDeviceWatchers();
            DeviceListSource.Source = listOfDevices;
        }
        bool SelectAllText = false;
        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            if (SelectAllText)
            {
                DataPackage dataPackage = new DataPackage();
                dataPackage.SetText(stringBuilder.ToString());
                Clipboard.SetContent(dataPackage);
                SelectAllText = false;
            }
            else
                recivceText.CopySelectionToClipboard();
        }
        private void AppBarButton_Click_1(object sender, RoutedEventArgs e)
        {
            recivceText.Text = "";
            stringBuilder.Clear();
            HomeViewMode.RecviceLength = 0;
        }
        private void AppBarButton_Click_2(object sender, RoutedEventArgs e)
        {
            SelectAllText = true;
            recivceText.SelectAll();
        }
        public class FontViewMode : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            int fontSize;
            uint recviceLength;
            uint sendAllLength;
            public FontViewMode()
            {
                this.fontSize = 16;
                this.recviceLength = 0;
                this.sendAllLength = 0;
            }
            public int FontSize
            {
                get { return this.fontSize; }
                set
                {
                    this.fontSize = value;
                    this.OnPropertyChanged();
                }
            }
            public uint RecviceLength
            {
                get
                {
                    return recviceLength;
                }
                set
                {
                    this.recviceLength = value;
                    this.OnPropertyChanged();
                }
            }
            public uint SendAllLength
            {
                get { return sendAllLength; }
                set
                {
                    this.sendAllLength = value;
                    this.OnPropertyChanged();
                }
            }
            public void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                // Raise the PropertyChanged event, passing the name of the property whose value has changed.
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        FontViewMode HomeViewMode = new FontViewMode();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (((Button)sender).Tag as string == "add")
                HomeViewMode.FontSize++;
            else
                HomeViewMode.FontSize--;
            recivceText.FontSize = HomeViewMode.FontSize;
        }
        public async Task serialWrite(string input)
        {
            if (dataWriter == null)
                return;
            dataWriter.WriteString(input);
            HomeViewMode.SendAllLength += await dataWriter.StoreAsync().AsTask();
        }

        private async Task<byte[]> serialRead()
        {
            try
            {
                Task<UInt32> loadAsyncTask = dataReader.LoadAsync(2048).AsTask();
                UInt32 bytesRead = 0;
                bytesRead = await loadAsyncTask;
                byte[] bytes = new byte[bytesRead];
                dataReader.ReadBytes(bytes);
                return bytes;
            }
            catch (Exception ex)
            {
                _ = ex;
                return null;
            }
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string text = sendText.Text.Replace("\r", "\r\n");
            if (text.First().Equals('#'))
            {
                text = text.Remove(0, 1);
                text = "<" + text + ">";
                byte[] bytes = Encoding.ASCII.GetBytes(text);
                byte sum = 0;
                foreach (byte b in bytes)
                {
                    sum += b;
                }
                text = $"[{text:s}{sum:X2}]";
            }
            await serialWrite(text);
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            baudRate = Convert.ToUInt32(e.AddedItems[0]);
            if (EventHandlerDevice.Current.Device != null)
                EventHandlerDevice.Current.Device.BaudRate = baudRate;
        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            dataBits = Convert.ToUInt16(e.AddedItems[0]);
            if (EventHandlerDevice.Current.Device != null)
                EventHandlerDevice.Current.Device.DataBits = dataBits;
        }

        private void ComboBox_SelectionChanged_2(object sender, SelectionChangedEventArgs e)
        {
            SerialParity parity;
            switch ((string)e.AddedItems[0])
            {
                case "None":
                    parity = SerialParity.None;
                    break;
                case "Odd":
                    parity = SerialParity.Odd;
                    break;
                case "Even":
                    parity = SerialParity.Even;
                    break;
                case "Mark":
                    parity = SerialParity.Mark;
                    break;
                case "Space":
                    parity = SerialParity.Space;
                    break;
                default:
                    parity = SerialParity.None;
                    break;
            }
            if (EventHandlerDevice.Current.Device != null)
                EventHandlerDevice.Current.Device.Parity = parity;
        }

        private void ComboBox_SelectionChanged_3(object sender, SelectionChangedEventArgs e)
        {
            SerialStopBitCount stopBitCount;
            switch ((string)e.AddedItems[0])
            {
                case "One":
                    stopBitCount = SerialStopBitCount.One;
                    break;
                case "OnePointFive":
                    stopBitCount = SerialStopBitCount.OnePointFive;
                    break;
                case "Two":
                    stopBitCount = SerialStopBitCount.Two;
                    break;
                default:
                    stopBitCount = SerialStopBitCount.One;
                    break;
            }
            if (EventHandlerDevice.Current.Device != null)
                EventHandlerDevice.Current.Device.StopBits = stopBitCount;
        }
        private void recivceTextScroll_ViewChanging(object sender, ScrollViewerViewChangingEventArgs e)
        {
            double height = recivceTextScroll.ScrollableHeight;
            double offset = recivceTextScroll.VerticalOffset;
            int charSize = 20000;
            int strlen = stringBuilder.Length;
            double position = strlen * (offset / height);
            if (position < charSize)
                position = 0;
            if (strlen - position >= charSize)
            {
                char[] chars = new char[charSize];
                stringBuilder.CopyTo((int)position, chars, charSize);
                MainWindow.Current.invoke(() => { recivceText.Text = new string(chars); });
            }
            else if (strlen >= charSize)
            {
                char[] chars = new char[charSize];
                stringBuilder.CopyTo((int)strlen - 20000, chars, charSize);
                MainWindow.Current.invoke(() => { recivceText.Text = new string(chars); });

            }
        }

        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            // Create a file picker
            FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();

            var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(MainWindow.Current);

            // Initialize the file picker with the window handle (HWND).
            WinRT.Interop.InitializeWithWindow.Initialize(savePicker, hWnd);

            // Set options for your file picker
            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Text", new List<string>() { ".txt" });
            // Default file name if the user does not type one in or select a file to replace
            var enteredFileName = "SerialText";
            savePicker.SuggestedFileName = enteredFileName;

            // Open the picker for the user to pick a file
            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(async state =>
                {
                    using (var steram = await file.OpenStreamForWriteAsync())
                    {
                        using (var sw = new StreamWriter(steram))
                        {
                            sw.Write(stringBuilder.ToString());
                        }
                    }
                }));
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Window window = WindowHelper.CreateWindow();
            Frame frame = new Frame();
            var hwnd = WindowNative.GetWindowHandle(window);
            var id = Win32Interop.GetWindowIdFromWindow(hwnd);
            var appWindow = AppWindow.GetFromWindowId(id);
            if (ApplicationData.Current.LocalSettings.Values["IsLarkWindowMaximum"] is true)
            {
                // 最大化
                User32.ShowWindow(hwnd, ShowWindowCommand.SW_SHOWMAXIMIZED);
            }
            if (ApplicationData.Current.LocalSettings.Values["LarkWindowRect"] is ulong value)
            {
                var rect = new WindowRect(value);
                // 屏幕区域
                var area = DisplayArea.GetFromWindowId(windowId: id, DisplayAreaFallback.Primary);
                // 若窗口在屏幕范围之内
                if (rect.Left > 0 && rect.Top > 0 && rect.Right < area.WorkArea.Width && rect.Bottom < area.WorkArea.Height)
                {
                    appWindow.MoveAndResize(rect.ToRectInt32());
                }
            }
            frame.RequestedTheme = ThemeHelper.RootTheme;
            switch (((MenuFlyoutItem)sender).Tag)
            {
                case "Wave":
                    frame.Navigate(typeof(WavePages), null);
                    break;
                case "Capture":
                    frame.Navigate(typeof(CommandCapture), null);
                    break;
            }
            window.Content = frame;
            window.Title = "新建窗口";
            window.Closed += Window_Closed;
            backStyleControl = new BackStyleControl(BackStyleControl.FastStyle.Mica, ref window);
            ((FrameworkElement)window.Content).ActualThemeChanged += Window_ThemeChanged;
            window.Activate();
        }

        BackStyleControl backStyleControl;
        private void Window_ThemeChanged(FrameworkElement sender, object args)
        {
            backStyleControl.SetConfigurationSourceTheme(((FrameworkElement)this.Content).ActualTheme);
        }
        private void Window_Closed(object sender, WindowEventArgs args)
        {
            var wpl = new User32.WINDOWPLACEMENT();
            var window = sender as Window;
            var hwnd = WindowNative.GetWindowHandle(window);
            var id = Win32Interop.GetWindowIdFromWindow(hwnd);
            var appWindow = AppWindow.GetFromWindowId(id);
            if (User32.GetWindowPlacement(hwnd, ref wpl))
            {
                ApplicationData.Current.LocalSettings.Values["IsLarkWindowMaximum"] = wpl.showCmd == ShowWindowCommand.SW_MAXIMIZE;
                var p = appWindow.Position;
                var s = appWindow.Size;
                var rect = new WindowRect(p.X, p.Y, s.Width, s.Height);
                ApplicationData.Current.LocalSettings.Values["LarkWindowRect"] = rect.Value;
            }
            backStyleControl.WindowsColose();
        }
        [StructLayout(LayoutKind.Explicit)]
        private struct WindowRect
        {
            [FieldOffset(0)]
            public short X;
            [FieldOffset(2)]
            public short Y;
            [FieldOffset(4)]
            public short Width;
            [FieldOffset(6)]
            public short Height;
            [FieldOffset(0)]
            public ulong Value;

            public int Left => X;
            public int Top => Y;
            public int Right => X + Width;
            public int Bottom => Y + Height;

            public WindowRect(int x, int y, int width, int height)
            {
                Value = 0;
                X = (short)x;
                Y = (short)y;
                Width = (short)width;
                Height = (short)height;
            }

            public WindowRect(ulong value)
            {
                X = Y = Width = Height = 0;
                Value = value;
            }

            public RectInt32 ToRectInt32()
            {
                return new RectInt32(X, Y, Width, Height);
            }
        }
        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (EventHandlerDevice.Current.Device != null)
            {
                switch (((CheckBox)sender).Tag)
                {
                    case "DTR":
                        EventHandlerDevice.Current.Device.IsDataTerminalReadyEnabled = true;
                        break;
                    case "RTS":
                        EventHandlerDevice.Current.Device.IsRequestToSendEnabled = true;
                        break;
                }
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (EventHandlerDevice.Current.Device != null)
            {
                switch (((CheckBox)sender).Tag)
                {
                    case "DTR":
                        EventHandlerDevice.Current.Device.IsDataTerminalReadyEnabled = false;
                        break;
                    case "RTS":
                        EventHandlerDevice.Current.Device.IsRequestToSendEnabled = false;
                        break;
                }
            }
        }
    }
}
